package net.area80.image
{
	import flash.display.Bitmap;
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;
	
	import net.area80.utils.Cleaner;
	import net.area80.utils.LoaderUtils;

	public class PhotoLoader extends Sprite
	{
		private var path:String;
		private var ldr:Loader;
		private var masker:Sprite;
		public var w:uint = 44;
		public var h:uint = 44;
		private var useMask:Boolean = true;
		

		public function PhotoLoader(_path:String,w:uint =44,h:uint=44, useMask:Boolean = true)
		{
			this.w = w;
			this.h = h;
			this.useMask = useMask;
			path = _path;
			if(path==""){
				//path= "http://static.ak.fbcdn.net/pics/q_silhouette.gif";
				return;
			}
			
			init();
			initListener();
		}
		private function init ():void {
			
			
			ldr = new Loader();
			ldr.load(new URLRequest(path));
			ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComp);
			ldr.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, loadError);
		}
		private function loadError (e:Event):void {
			init();
		}
		private function loadComp(e:Event):void {
			var scale:Number = 1;
		
			if(w!=0 || h!=0) {
				if(w == 0 && h!=0) {
					scale = h/ldr.height;
				} else if (h == 0 && w != 0) {
					scale = w/ldr.width;
				} else {
					scale = Math.max(w/ldr.width,h/ldr.height);
				}
			}
			//if(scale>1) scale = 1;
			try {
				Bitmap(ldr.content).smoothing = true;
			} catch (e:Error){}
			
			//if(scale >1) {
				ldr.scaleX = ldr.scaleY = scale;
			//}
			addChild(ldr);
			if(w!=0 && h!= 0 && useMask) {
				masker = new Sprite();
				masker.graphics.beginFill(0x0000);
				masker.graphics.drawRect(0,0,w,h);
				addChild(masker);
				ldr.mask = masker;
			}
			dispatchEvent(new Event(Event.COMPLETE));
		}
		private function initListener():void {
			
			Cleaner.disposeOnRemoved(this);
		}
		public function dispose ():void {
			LoaderUtils.clearLoader(ldr);
		}
		
	}
}